<?php
class Session
{
	
	private $sessionId;
	private $user;
	
	const salt =	"nj)<7HDHT/fBKZ4@nq]H7p_b=4F62wB2F8t*X3[uHAL2Vts&HG"; // change to wathever you want
	const pepper =	"4&%z8vyNZ<kx8PRA672Yfnj])MyC8zhJ9/9pc:b%Tdd>4NCt+F"; // change to wathever you want
	
	function __construct()
	{
	}
	
	public function getSessionId()
	{
		return $this->sessionId;
	}
	
	public function setSessionId($ssid)
	{
		$this->sessionId = $ssid;
		$_SESSION['ssid'] = $ssid;
	}
	
	public static function getFromSession($param)
	{
		return $_SESSION[$param];
	}
	
	private function newSession($user)
	{
		$this->user = new User($user);
			
		// Makes the session ID
		$secarray = array();
		$secarray[0] = sha1($_SERVER['HTTP_USER_AGENT']); // link session to a specific browser
		$secarray[1] = sha1($_SERVER['REMOTE_ADDR']); // link the session to a specific IP
		$secarray[2] = sha1($_SERVER['SERVER_ADDR']); // anti-phishing :)
		$secarray[3] = sha1(self::salt);
		$secarray[4] = sha1(self::pepper);
		$secarray[5] = sha1($this->user->getLogin());
		
		// scramble to avoid replay attacks
		shuffle($secarray);
		
		foreach($secarray as $secitem)
			$this->sessionId .= $secitem;
		
		$this->sessionId = sha1($this->sessionId);
		$this->user->setSession($this->sessionId);
		
		// Sets expiration time
		//$duration = (60 * 60 * 24) * 10; // 10 days
		$duration = 60 * 60; // 1 hour
		$end = time() + $duration;
		
		// Sets the db
		$d = new Database();
		$uid = $d->secure($this->user->getId());
		$d->query("DELETE FROM sessions WHERE uid = '$uid';"); // first, delete previous session
		$data['uid'] = $uid;
		$data['ssid'] = $this->sessionId;
		$data['end'] = $end;
		$d->insert('sessions',$data); // insert new session
		
		// Sets the server variable
		$_SESSION['ssid'] = $this->sessionId;
		
		// Sets the cookies
		setcookie('session', $this->sessionId, $end ); // ssid
		setcookie('user', $user, $end ); // login
				
		return true;
	}
	
	public function loadSession($login,$password)
	{	
		// Check user authentication
		$user = new User($login);
		if(!$user->chkPwd($password))
			return false;
		// at this point, provided password matches and user is supposed to be legit
		
		$this->user = $user;
				
		// there is no session cookie
		if(!isset($_COOKIE['session']) or empty($_COOKIE['session']))
			return $this->newSession($login);
		
		// read from user
		$cookie_ssid = $_COOKIE['session'];
		
		// read from db
		$d = new Database();
		$ar['uid'] = $this->user->getId();
		$d->select('sessions','*',$ar);
		
		if($d->num_rows() < 1) // user doesn't exist
			return false;
		elseif($d->num_rows() > 1) // more than 1 user with this id, we have a security issue here
			return false; // should never happen, since 'id' are UNIQUE primary keys

		$data = $d->fetch_all();
		$ss = $data[0];
		
		$db_ssid = $ss['ssid'];
		$ssend = $ss['end'];
		
		// session expired
		//if($ssend < time())
		//	return false;
				
		// sessions don't match
		if($db_ssid != $cookie_ssid)
			return false;

		// everything's ok
		$this->sessionId = $db_ssid;
		$this->user->setSession($db_ssid);
		$_SESSION['ssid'] = $db_ssid;
		return true;
	}
	
	public function chkSession()
	{		
		// there is no session cookie
		if(!isset($_COOKIE['session']) or empty($_COOKIE['session']))
			return false;
			
		// there is no user cookie
		if(!isset($_COOKIE['user']) or empty($_COOKIE['user']))
			return false;
		
		// get the user and cookie ssid
		$cookie_ssid = $_COOKIE['session'];
		$user = $_COOKIE['user'];
		
		// get the ssid of this user from the db
		$u = new User($user);
		$db_ssid = $u->getSession();
		
		if(!$db_ssid) // db_ssid is a boolean, set to false, unless changed to an actual ssid
			return false;
			
		// cookie and db don't match
		if($db_ssid != $cookie_ssid)
			return false;
				
		// everything's ok
		$this->setSessionId($db_ssid);
		return true;
	}
	
	public static function delete($ssid)
	{
		$d = new Database();
		$ssid = $d->secure($ssid); // prevent injection from session/cookie alteration
		$d->query("DELETE FROM sessions WHERE ssid = '$ssid';");
	}
	
}
?>